package org.example.domain.strategy.service.rule.chain.factory;

import lombok.*;
import org.example.domain.strategy.model.entity.StrategyEntity;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.rule.chain.ILogicChain;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class DefaultChainFactory {
    /**
     * DefaultChainFactory 的实例化：Spring 会自动创建 DefaultChainFactory 的实例，因为该类被注解为 @Service，Spring 会把它注册为一个 Bean。
     * logicChainGroup 和 repository 的注入：Spring 会自动通过构造器注入这两个依赖。
     * logicChainGroup 是一个 Map，通常会在配置类中定义并作为一个 Spring Bean；
     * repository 是 IStrategyRepository 的实现类，Spring 会自动注入合适的实现。
     */

    protected IStrategyRepository repository;
    private final Map<String, ILogicChain> logicChainGroup;

    public DefaultChainFactory(Map<String, ILogicChain> logicChainGroup, IStrategyRepository repository) {
        this.logicChainGroup = logicChainGroup;
        this.repository = repository;
    }

    /**
     * 通过策略ID，构建责任链
     *
     * @param strategyId 策略ID
     * @return LogicChain
     */

    public ILogicChain openLogicChain(Long strategyId){

        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruleModels = strategyEntity.ruleModels();

        if(null == ruleModels || 0 == ruleModels.length){
            return  logicChainGroup.get("default");
        }

        ILogicChain logicChain = logicChainGroup.get(ruleModels[0]);
        ILogicChain currentLogicChain = logicChain;

        for (int i = 1; i < ruleModels.length; i++) {
            ILogicChain nextLogicChain = logicChainGroup.get(ruleModels[i]);
            currentLogicChain = currentLogicChain.appendNext(nextLogicChain);
        }

        currentLogicChain.appendNext(logicChainGroup.get("default"));

        return logicChain;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /** 抽奖奖品ID - 内部流转使用 */
        private Integer awardId;
        /**  */
        private String logicModel;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;
        private final String info;

    }




}



